import {createSlice, nanoid, PayloadAction} from "@reduxjs/toolkit";
import {ComponentPropsType} from "../../components/QuestionComponents";
import {produce} from "immer";
import {getNextSelected, insertNewComponent} from "./util";
import {message} from "antd";
import QuestionParagraph from "../../components/QuestionComponents/QuestionParagraph/Components";
import {arrayMove} from "@dnd-kit/sortable";

/**
 *             {
 *               fe_id: Random.id(),
 *               type: 'questionTitle',//组件类型，不能重复，前后端统一
 *               title: '标题',
 *               props: {
 *                 text: '一行标题11',
 *                 level: 1,
 *                 isCenter: true
 *               }
 */
// 后台返回的单个组件列表信息格式
export type ComponentsInfoTypes = {
  fe_id: string,//前端生成的id，服务端mongodb不承认这种格式，所以自定义fe_id
  type: string,
  title: string,
  isHidden?: boolean,
  isLocked?: boolean,
  props: ComponentPropsType
}
// 组件列表
export type ComponentsStateType = {
  selectedId: string,
  componentList: ComponentsInfoTypes[],
  copyComponent: ComponentsInfoTypes | null
}
// 初始化组件列表
const INIT_STATE: ComponentsStateType = {
  selectedId: '',
  componentList: [],
  copyComponent: null
}

const componentsRuducer = createSlice({
  initialState: INIT_STATE,
  name: 'components',
  reducers: {
    resetComponent(state: ComponentsStateType, action: PayloadAction<ComponentsStateType>) {
      return action.payload
    },
    changeSelectedId: produce((drart: ComponentsStateType, action: PayloadAction<string>) => {
      drart.selectedId = action.payload
      console.log('drart.selectedId', drart.selectedId)
    }),
    addComponent: produce((drart: ComponentsStateType, action: PayloadAction<ComponentsInfoTypes>) => {
      const {selectedId} = drart
      const newComponent = action.payload
      insertNewComponent(drart, newComponent)
    }),
    updateComponent: produce((draft: ComponentsStateType, action: PayloadAction<{
      fe_id: string,
      newProps: ComponentPropsType
    }>) => {
      const {fe_id, newProps} = action.payload
      const curCom = draft.componentList.find(c => c.fe_id === fe_id)
      console.log('QuestionParagraph', QuestionParagraph)
      if (curCom) {
        curCom.props = newProps
      }
    }),
    deleteComponent: produce((draft: ComponentsStateType) => {
      const {selectedId: removeId, componentList} = draft
      if (removeId) {
        draft.selectedId = getNextSelected(removeId, componentList)//先设置新的selectedId
        const index = componentList.findIndex(c => c.fe_id === removeId)
        draft.componentList.splice(index, 1)
      } else {
        message.error("请选中要删除的组件")
      }
    }),
    changeComponentIsHidden: produce((draft: ComponentsStateType, action: PayloadAction<{
      fe_id: string,
      isHidden: boolean
    }>) => {
      const {componentList} = draft
      const {fe_id, isHidden} = action.payload
      //   先从componentList找到当前的component

      if (!fe_id) return
      // 重新计算selected
      let selected = ''
      if (isHidden) {
        //   隐藏
        selected = getNextSelected(fe_id, componentList)//先设置新的selectedId
      } else {
        //   显示
        selected = fe_id
      }
      draft.selectedId = selected
      const curCom = draft.componentList.find(c => c.fe_id === fe_id)
      if (!curCom) return;
      curCom.isHidden = isHidden
    }),
    toggleComponentLocked: produce((draft: ComponentsStateType, action: PayloadAction<{ fe_id: string }>) => {
      const {componentList} = draft
      const {fe_id} = action.payload
      const curCom = componentList.find(c => c.fe_id === fe_id)
      if (curCom) {
        curCom.isLocked = !curCom.isLocked
      }
    }),
    copySelectedComponent: produce((draft: ComponentsStateType) => {
      const {componentList, selectedId} = draft
      const copyCom = componentList.find(c => c.fe_id === selectedId)
      if (!copyCom) return
      draft.copyComponent = copyCom
    }),
    pasteComponent: produce((draft: ComponentsStateType) => {
      const {componentList, selectedId, copyComponent} = draft
      if (!copyComponent) return
      if (!selectedId) return;
      // 要从新修改fe_id!!!!
      copyComponent.fe_id = nanoid()
      insertNewComponent(draft, copyComponent)
    }),
    selectPrevComponent: produce((draft: ComponentsStateType) => {
      const {selectedId, componentList} = draft
      const selectedIndex = componentList.findIndex(c => c.fe_id === selectedId)
      if (selectedIndex < 0) return//没有选中
      if (selectedIndex <= 0) return;//选中的是第一个
      draft.selectedId = componentList[selectedIndex - 1].fe_id
    }),
    selectNextComponent: produce((draft: ComponentsStateType) => {
      const {selectedId, componentList} = draft
      const selectedIndex = componentList.findIndex(c => c.fe_id === selectedId)
      if (selectedIndex < 0) return//没有选中
      if (selectedIndex + 1 === componentList.length) return;//选中的是最后一个
      draft.selectedId = componentList[selectedIndex + 1].fe_id
    }),
    moveComponent: produce((draft: ComponentsStateType, action: PayloadAction<{
      oldIndex: number,
      newIndex: number
    }>) => {
      const {oldIndex, newIndex} = action.payload
      const {componentList} = draft
      draft.componentList = arrayMove(componentList, oldIndex, newIndex)
    })
  }
})
export const {
  resetComponent,
  changeSelectedId,
  deleteComponent,
  addComponent,
  updateComponent,
  changeComponentIsHidden,
  toggleComponentLocked,
  copySelectedComponent,
  pasteComponent,
  selectPrevComponent,
  selectNextComponent,
  moveComponent,

} = componentsRuducer.actions
export default componentsRuducer.reducer
